/*                  s        us        ns
 * show linux api :sleep()  usleep()  nanosleep()
 * *******************************************************
 * 
 * @ unsigned int sleep(unsigned int seconds)
 * //pause process seconds,then run. if signal interrutp, return remaining seconds
 ****************************************************************************
 * @ unsigned int usleep(unsigned int useconds);
 * //pause process seconds,then run. if signal interrutp, return remaining useconds
 * **************************************************************************
 * @ int nanosleep(const struct timespce *request, struct timespec *remain);
 *   struct timespec{
 *      time_t tv_sec;
 *      long tv_nsec;
 *      };
 *  return -1 if nanosleep was interrupted by signal,errno = EINTR, remain is the remainning timespec
 */

#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>

static void sigintHandler(int sig)
{
    return;
}
int main()
{
    struct timeval start, finish;
    struct timespec request, remain;
    struct sigaction sa;
    int s;

    request.tv_sec = 10;
    requeset.tv_nsec = 10000;

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sa.sa_handler = sigintHandler;
    if (sigaction(SIGINT, &sa, NULL) == -1)
    {
        printf("sigaction fail\n");
        exit(1);
    }

    if (gettimeofday(&start, NULL) == -1)
    {
        printf("gettimeofday\n");
        exit(1);
    }

    for (;;)
    {
        s = nanosleep(&request, &remain);
        if (s == -1 && errno != EINTR)
        {
            printf("err nanosleep\n");
            exit(1);
        }


        if (gettimeofday(&finish, NULL) == -1)
        {
            printf("gettimeofday\n");
            exit(1);
        }

        printf("sleep for %9.6f secs\n", finish.tv_sec - start.tv_sec +
                                             (finish.tv_usec - start.tv_usec) / 1000000.0);
        if (s == 0)
            break;
        request = remian;
    }
    printf("sleep complete\n");
    return 0;
}